package com.zzyl.nursing.service.impl;

import java.io.ObjectInputFilter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * 入住Service业务层处理
 *
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private IElderService elderService;

    @Autowired
    private IBedService bedService;

    @Autowired
    private IContractService contractService;

    @Autowired
    private ICheckInConfigService checkInConfigService;

    @Autowired
    private ICheckInService iCheckInService;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    public void apply(CheckInApplyDto dto) {
        //检查老人是否已经入住
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .one();
        if (elder != null) {
            elder.setId(elder.getId());
        }
        //更新床位状态
        Bed bed = new Bed();
        //设置床位id,更改状态
        bed.setBedStatus(1);
        //更新床位信息
        bedService.updateBed(bed);
        //判断床位是否空闲
        Bed newbed = bedService.getById(dto.getCheckInConfigDto().getBedId());
        if (newbed == null) {
            throw new RuntimeException("床位已被入住");
        }
        //新增或者更新老人
        // 将入住老人DTO对象转换为Elder实体对象
        Elder newelder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        newelder.setStatus(1);
        newelder.setBedNumber(newbed.getBedNumber());
        newelder.setBedId(newbed.getId());
        if (elder!=null){
            elder.setId(newelder.getId());
        }
        elderService.saveOrUpdate(newelder);
        //新增签约办理
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(newelder.getId());
        contract.setElderName(newelder.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setStatus(LocalDateTime.now().isAfter(dto.getCheckInConfigDto().getStartDate()) ? 1 : 0);
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contractService.save(contract);
        //新增入住信息
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(newelder.getId());
        checkIn.setElderName(newelder.getName());
        checkIn.setIdCardNo(newelder.getIdCardNo());
        checkIn.setBedNumber(newelder.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setId(newelder.getBedId());
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        this.save(checkIn);
        //新增入住配置
        CheckInConfig config = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        config.setCheckInId(checkIn.getId());
        checkInConfigService.save(config);
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getCheckInDetail(Long id) {
        CheckInDetailVo detailVo = new CheckInDetailVo();

        CheckIn checkIn = this.getById(id);

        CheckInElderVo elderVo = new CheckInElderVo();
        Elder elder = elderService.lambdaQuery().eq(Elder::getId, checkIn.getElderId()).one();
        BeanUtil.copyProperties(elder,elderVo,true);
        detailVo.setCheckInElderVo(elderVo);

        Contract contract = contractService.lambdaQuery().eq(Contract::getElderId, checkIn.getElderId()).one();
        detailVo.setContract(contract);

        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckInConfig config = checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()).one();
        // 将config对象的属性复制到checkInConfigVo对象中，忽略空值
        BeanUtil.copyProperties(config, checkInConfigVo, true);
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        detailVo.setCheckInConfigVo(checkInConfigVo);

        List<ElderFamilyVo> remark = JSONUtil.toList(elder.getRemark(), ElderFamilyVo.class);
        if (remark != null) {
            detailVo.setElderFamilyVoList(remark);
        }
        return detailVo;
    }

}
